<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/21 0021
 * Time: 15:19
 */
namespace Api\Controller;


class UserController extends BaseController
{
    /**
     * 获取小程序推广码
     * @param $unionid
     * @return mixed|string
     */
    public function getCoade(){

        $unionid = I('id');
        if(empty($unionid)||$unionid==''){
            $this->error('参数不存在');
        }
        $userInfo = M('usermember')->where(['id'=>$unionid])->find();
        if(empty($userInfo))$this->error('用户不存在');
        function getaccess_token(){
            $appid = 'wxcd8cb69e4c15cbfb'; // 小程序APPID
            $secret = 'a2383fcb0f92a465f718875850e2bff1'; // 小程序secret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
            $data = curl_exec($ch);
            curl_close($ch);
            $data = json_decode($data,true);
            return $data['access_token'];
        }
        function set_msg($unionid){
            $access_token = getaccess_token();
            $data2=array(
                "scene"=>$unionid,
                "page"=>"pages/login/login",
                "width"=>400
            );
            $data2 = json_encode($data2);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token."";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
            $data = curl_exec($ch);
            curl_close($ch);

            return $data;
        }
        $img=set_msg($unionid);

        $img=base64_encode($img);
        $base64_image_content="data:image/jpeg;base64,".$img;

        $ename=rand(100,999).time();
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = substr($_SERVER['SCRIPT_FILENAME'],0,-9).'Uploads/Promotion/';
            if(!file_exists($new_file))
            {
                mkdir($new_file, 0777);
            }
            $wname=$ename.".{$type}";
            $new_file = $new_file.$wname;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            }else{
                echo '新文件保存失败';
            }
        }
        M('usermember')->where(['id'=>$unionid])->save(['pro_code'=>'/Uploads/Promotion/'.$wname]);
        $this->success('推广二维码已生成','/Uploads/Promotion/'.$wname);
    }
}